package com.framework.service.impl;

import cn.dev33.satoken.util.SaResult;
import com.framework.entity.Role;
import com.framework.entity.UserRole;
import com.framework.repository.UserRoleRepository;
import com.framework.service.UserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description: 用户-角色服务接口服务接口实现
 * @Author: JamesYao
 * @DateTime: 2024/2/19 17:20
 */

@Service
@RequiredArgsConstructor
@Transactional
public class UserRoleServiceImpl implements UserRoleService {

    private final UserRoleRepository userRoleRepository;

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 根据用户ID查找角色列表
     * 使用Hibernate Criteria查询方式查找角色列表
     * 另一条查询语句：select r from Role r where r.id in (select ur.roleId from UserRole ur where ur.userId = :userId)
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<Role> findRolesByUserId(UUID userId) {
        // 使用Hibernate Criteria查询方式查找角色列表
        String jpql = "SELECT r FROM Role r JOIN UserRole ur ON r.id = ur.roleId WHERE ur.userId = :userId";
        return entityManager.createQuery(jpql, Role.class)
                .setParameter("userId", userId)
                .getResultList();
    }

    @Override
    public void updateUserRole(UserRole userRole) {
        UserRole userRole1 = userRoleRepository.findById(userRole.getId()).orElseThrow();
        userRole1.setRoleId(userRole.getRoleId());

    }


    /**
     * 保存用户角色信息
     *
     * @param userRole 用户角色信息
     * @return 保存结果
     */
    @Override
    public SaResult saveUserRole(UserRole userRole) {
        // 保存用户角色信息到数据库
        userRoleRepository.save(userRole);
        return SaResult.ok();
    }

}
